<template>
	<Modal scrollable v-model="modal" @on-cancel="onCancel" title="商品详情" class-name="vertical-center-modal" width="950">
		<Form ref="activeGoodsDetail" :model="activeGoodsDetail" :rules="rules" class="attrFrom" :label-width="labelWidth"
			:label-position="labelPosition" @submit.native.prevent>
			<Row :gutter="24">
				<Col span="24">
				<Col span="24" class="mb15">
				<FormItem label="商品名称" prop="good_name" class="vertical-layout">
					<Input :maxlength="20" v-model="activeGoodsDetail.good_name" disabled />
				</FormItem>
				</Col>
				<Col span="24" class="mb15">
				<FormItem label="sku信息" prop="sku" class="vertical-layout">
					<!-- <table height="500">
						<thead>
							<tr>
								<th>SKU编号</th>
								<th>规格</th>
								<th class="text-right">原价(元)</th>
								<th class="text-right">活动价(元)</th>
								<th class="text-center">在库库存</th>
								<th class="text-center">活动库存</th>
								<th class="text-center">优惠力度(%)</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="sku in activeGoodsDetail.skus" :key="sku.id">
							    <td>{{ sku.sku }}</td>
							    <td>{{ sku.suk }}</td>
							    <td class="text-right">
							        <span class="original-price">{{ sku.original_price.toFixed(2) }}</span>
							    </td>
							    <td class="text-right">
							        <span class="sale-price">{{ sku.activity_price.toFixed(2) }}</span>
							    </td>
							    <td class="text-center" :class="{ 'stock-warning': sku.stock < 50 }">

							        <div v-for="(warehouse, index) in sku.product_stock_info" :key="index" class="warehouse-info">
							            <div class="warehouse-name">{{ warehouse.warehouse }}:</div>
							            <div class="warehouse-stock">{{ warehouse.stock }}</div>
							        </div>
							    </td>
							    <td class="text-center" :class="{ 'stock-warning': getTotalActivityStock(sku) < 20 }">

							        <div v-for="(warehouse, index) in sku.product_stock_info" :key="index" class="activity-stock-input">
							            <Input 
							                :value="getActivityStockValue(sku, index)" 
							                disabled 
							                size="small"
							                class="stock-input"
							            />
							            <div class="warehouse-label">{{ warehouse.warehouse }}</div>
							        </div>
							    </td>
							    <td class="text-center">
							        <span class="discount-badge">
							            {{ sku.discount_rate.toFixed(2) }}%
							        </span>
							    </td>
							</tr>
						</tbody>
					</table> -->
				<Table border :columns="skuColumns" :data="activeGoodsDetail.skus" editable max-height="500">
								
					<template slot="activity_price" slot-scope="{ row, index }">
					    <span class="sale-price">{{ row.activity_price.toFixed(2) }}</span>
					</template>
					<template slot="warehouse" slot-scope="{ row, index }">
					    <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
					                {{warehouse.warehouse}}
					                <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
					              </div>
					</template>
					<template slot="stock" slot-scope="{ row, index }">
					    <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
					                <Input
					                  :value="warehouse.stock"
					                  disabled
					                />
					                <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
					              </div>
					</template>
					<template slot="activity_stock" slot-scope="{ row, index }">
					  <div v-for="(warehouse, wIndex) in row.product_stock_info" :key="wIndex">
					    <Input
					      :value="getActivityStockValue(row, wIndex)"
					      :placeholder="$t('page.activity.event_stock')"
					      @input="val => handleStockInput(val, index, wIndex)"
					      :disabled="warehouse.stock == 0"
					      type="number"
					      min="0"
					      :max="warehouse.stock"
					    />
					    <div style="margin: 10px 0;" v-if="wIndex < row.product_stock_info.length - 1"></div>
					  </div>
					</template>
					<template slot="discount_rate" slot-scope="{ row, index }">
					    <span class="discount-badge">
					        {{ row.discount_rate.toFixed(2) }}%
					    </span>
					</template>
				</Table>
				</FormItem>
				</Col>
				</Col>

			</Row>

		</Form>
		<div slot="footer">
			<Button type="primary" @click="cancle">关闭</Button>
			<!-- <Button
                    type="primary"
                    :loading="modal_loading"
                    @click="handleSubmit('formDynamic')"
            >{{$t('page.product.save')}}</Button
            > -->
		</div>
	</Modal>
</template>

<script>
	import {
		mapState
	} from "vuex";

	import Setting from "@/setting";
	import util from "@/libs/util";
	export default {
		name: "addAttr",
		props: {
			activeGoodsDetail: {
				type: Array,
				default: () => {}
			},
		},
		data() {
			return {
				header: {},
				fileUrl: Setting.apiBaseURL + "/file/upload",
				spinShow: false,
				modal_loading: false,
				dialogVisible: false,
				// allTags: [
				//         {
				// 			label:"标签一",
				// 			value:"1"
				// 		},
				// 		{
				// 			label:"标签二",
				// 			value:"2"
				// 		},
				//       ],
				grid: {
					xl: 3,
					lg: 3,
					md: 12,
					sm: 24,
					xs: 24,
				},
				skuColumns: [{
						title: "SKU 编号",
						key: "sku",
						width: 80
					},
					{
						title: "规格",
						key: "suk"
					},
					{
						title: "原价(元)",
						key: "original_price"
					},
					{
						title: "活动价(元)",
						key: "activity_price",
						slot: "activity_price"
					},
					{
						title: "仓库",
						key: "warehouse",
						slot: "warehouse"
					},
					{
						title: "在库库存",
						key: "stock",
						slot: "stock"
					},
					{
						title: "活动库存",
						key: "activity_stock",
						slot: "activity_stock"
					},
					{
						title: "优惠力度(%)",
						key: "discount_rate",
						slot: "discount_rate"
					}
				],
				modal: false,
				index: 1,
				skus: [{
						id: 1,
						skuCode: 'SKU1001',
						specification: '黑色 8+128GB',
						originalPrice: 3999,
						activityPrice: 3599,
						stock: 150,
						activityStock: 80,
						discount: 10
					},
					{
						id: 2,
						skuCode: 'SKU1002',
						specification: '黑色 8+256GB',
						originalPrice: 4399,
						activityPrice: 3799,
						stock: 120,
						activityStock: 65,
						discount: 13.6
					},

				],
				rules: {
					rule_name: [{
						required: true,
						message: "请输入分类名称",
						trigger: "blur"
					}, ],
					first_name: [{
						required: true,
						message: "请输入名",
						trigger: "blur"
					}, ],
					last_name: [{
						required: true,
						message: "请输入姓",
						trigger: "blur"
					}, ],
					phone: [{
						required: true,
						message: "请输入电话",
						trigger: "blur"
					}, ],
					company: [{
						required: true,
						message: "请输入公司名称",
						trigger: "blur"
					}, ],
					address: [{
						required: true,
						message: "请输入地址",
						trigger: "blur"
					}, ],
					email: [{
							required: true,
							message: '请输入邮箱地址',
							trigger: 'blur'
						},
						{
							pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
							message: '邮箱格式不正确',
							trigger: 'blur'
						}
					]
				},
				phoneExist: false,
				emailExist: false,
				formDynamic: {
					good_name: "",
					last_name: "",
					phone: "",
					email: "",
					address: "",
					language: "1",
					state: "1",
					country: "20",
					company: "",
					apartment: "",
					city: "",
					zip_code: "",
					selectedTags: [],
					file_url: [],
				},
				uploadFileList: [],
				images: [],
				others: [],
				urlList: [],
				attrsName: "",
				attrsVal: "",
				formDynamicNameData: [],
				isBtn: false,
				formDynamicName: [],
				results: [],
				result: [],
				ids: 0,
				title: "添加客户信息",
			};
		},
		computed: {
			...mapState("admin/layout", ["isMobile"]),
			labelWidth() {
				return this.isMobile ? undefined : 150;
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
		},
		mounted() {
			this.getToken();
		},
		methods: {
			// ...mapMutations('store/layout', [
			//     'setCopyrightShow'
			// ]),
			// 获取活动库存值
			    getActivityStockValue(sku, warehouseIndex) {
			        if (sku.activity_stock && sku.activity_stock.length > warehouseIndex) {
			            return sku.activity_stock[warehouseIndex];
			        }
			        return 0;
			    },
			    
			    // 计算总活动库存（用于警告判断）
			    getTotalActivityStock(sku) {
			        if (!sku.activity_stock) return 0;
			        return sku.activity_stock.reduce((total, stock) => total + stock, 0);
			    },
			getToken() {
				this.header["Authori-zation"] = "Bearer " + util.cookies.get("token");
			},
			// 上传成功
			handleSuccess(res, file, fileList) {
				this.fileGouzi = file
				console.log("this.formDynamic.file_url", this.formDynamic.file_url)
				if (res.code === 0) {
					if (!Array.isArray(this.formDynamic.file_url)) {
						this.formDynamic.file_url = [];
					}
					// this.formDynamic.file_url = res.data.src;
					this.formDynamic.file_url.push(res.data.src)
					this.$Message.success(res.msg);
				} else {
					this.$Message.error(res.msg);
				}
			},
			getFileName(url) {
				try {
					return url.split('/').pop();
				} catch (e) {
					return url;
				}
			},
			//检查手机是否存在
			checkPhoneExist() {
				let data = {
					id: this.ids,
					phone: this.formDynamic.phone
				}
				console.log("data", data)
				checkPhoneExistApi(data)
					.then((res) => {
						console.log("res---", res)
						if (res.data.exists) {
							this.phoneExist = true
							this.formDynamic.phone = ""
							this.$Message.warning('电话号码已存在')
						} else {
							this.phoneExist = false
						}
					})
					.catch((res) => {
						this.$Message.error('检查电话号码失败');
					});
			},
			checkEmailExist() {
				// alert(123)
				let data = {
					id: this.ids,
					email: this.formDynamic.email
				}
				checkEmailExistApi(data)
					.then((res) => {
						console.log("res1---", res)
						if (res.data.exists) {
							this.emailExist = true
							this.formDynamic.email = ""
							this.$Message.warning('邮箱已存在')
						} else {
							this.emailExist = false
						}
					})
					.catch((res) => {
						this.$Message.error('检查邮箱失败');
					});
			},
			removeTag(tag) {
				// 移除单个标签
				this.formDynamic.selectedTags = this.formDynamic.selectedTags.filter(t => t !== tag);
			},
			handleSaveTags(tags) {
				this.formDynamic.selectedTags = tags;
				console.log('保存的标签:', tags);
			},
			onCountryChange(value) {
				console.log('国家变更，传给父组件的值：', value);
				// 触发事件传给父组件
				this.$emit('countryChanged', value);
			},
			onCancel() {
				this.clear();
			},
			// getLanguagesList(){

			// 		  languagesListApi(this.formDynamic).then((res) => {
			// 			  this.languagesList = res.data.list;
			// 		  }).catch((err)=>{
			// 		    // this.loading = false;
			// 		    this.$Message.error(err.msg);
			// 		  })

			// },
			// 添加按钮
			addBtn() {
				if (this.formDynamic.rule_name.trim() == '') {
					return this.$Message.error('请输入分类名称');
				}
				this.isBtn = true;
			},
			// 详情
			getIofo(row) {
				this.spinShow = true;
				this.ids = row.id;
				this.title = "编辑客户";
				storeCustomerInfoApi(row.id)
					.then((res) => {
						this.formDynamic = res.data.info;
						// this.splitFilesByType(res.data.info.file_url)
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			isImageFile(url) {
				const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
				const ext = url.split('.').pop().toLowerCase();
				return imageTypes.includes(ext);
			},

			splitFilesByType(fileArray) {
				if (!Array.isArray(this.formDynamic.images)) {
					this.images = [];
				}
				console.log('filearr', fileArray)
				fileArray.forEach(url => {

					if (this.isImageFile(url)) {
						this.images.push(url);
						console.log('this.images', this.images);
					} else {
						this.others.push(url);
						console.log('this.others', this.others);
					}
				});
				console.log('images', this.images)
				// return { images, others };
			},
			// 提交
			handleSubmit(name) {
				this.$refs[name].validate((valid) => {
					if (!valid) return;
					if (valid) {
						if (this.phoneExist) {
							return this.$Message.warning("手机号重复,请重新填写！");
						}
						if (this.emailExist) {
							return this.$Message.warning("邮箱重复,请重新填写！");
						}
						if (this.formDynamic.first_name.length == 0) {
							return this.$Message.warning("请填写客户名称！");
						}
						if (this.formDynamic.address.length == 0) {
							return this.$Message.warning("请填写客户地址！");
						}
						if (this.formDynamic.email.length == 0) {
							return this.$Message.warning("请填写客户邮箱！");
						}
						if (this.formDynamic.phone.length == 0) {
							return this.$Message.warning("请填写客户手机！");
						}

						this.modal_loading = true;

						setTimeout(() => {
							storeCustomreAddApi(this.formDynamic, this.ids)
								.then((res) => {
									this.$Message.success(res.msg);
									setTimeout(() => {
										this.modal = false;
										this.modal_loading = false;
									}, 500);
									setTimeout(() => {
										this.$emit("getList");
										this.clear();
									}, 600);
								})
								.catch((res) => {
									this.modal_loading = false;
									this.$Message.error(res.msg);
								});
						}, 1200);
					} else {
						return false;
					}
				});
			},
			clear() {
				this.$refs["formDynamic"].resetFields();
				this.formDynamic.spec = [];
				this.formDynamic.first_name = "";
				this.formDynamic.last_name = "";
				this.formDynamic.phone = "";
				this.formDynamic.email = "";
				this.formDynamic.address = "";
				this.formDynamic.language = "1";
				this.formDynamic.state = "1";
				this.formDynamic.country = "20";
				this.formDynamic.company = "";
				this.formDynamic.apartment = "";
				this.formDynamic.city = "";
				this.formDynamic.zip_code = "";
				this.formDynamic.selectedTags = [];
				this.formDynamic.file_url = [];
				console.log("this.formDynamic.file_urlqqq", this.formDynamic.file_url)
				this.isBtn = false;
				this.ids = 0;
				this.title = "添加客户";
				this.attrsName = "";
				this.attrsVal = "";
				this.images = [];
				this.others = [];
				this.urlList = [];
				this.uploadFileList = [];
				this.$nextTick(function() {
					if (_this6.$refs.uploadRef) {
						_this6.$refs.uploadRef.clearFiles();
					}
				});
			},
			// 取消
			offAttrName() {
				this.isBtn = false;
			},
			cancle() {
				this.modal = false;
				this.clear()
			},
			// 删除
			handleRemove(index) {
				this.formDynamic.spec.splice(index, 1);
			},
			// 删除属性
			handleRemove2(item, index) {
				item.splice(index, 1);
			},
			// 添加规则名称
			createAttrName() {
				if (this.attrsName && this.attrsVal) {
					let data = {
						value: this.attrsName,
						detail: [this.attrsVal],
					};
					this.formDynamic.spec.push(data);
					var hash = {};
					this.formDynamic.spec = this.formDynamic.spec.reduce(function(
							item,
							next
						) {
							/* eslint-disable */
							hash[next.value] ? "" : (hash[next.value] = true && item.push(next));
							return item;
						},
						[]);
					this.attrsName = "";
					this.attrsVal = "";
					this.isBtn = false;
				} else {
					this.$Message.warning("请添加规格名称或规格值");
				}
			},
			// 添加属性
			createAttr(num, idx) {
				if (num) {
					this.formDynamic.spec[idx].detail.push(num);
					var hash = {};
					this.formDynamic.spec[idx].detail = this.formDynamic.spec[
						idx
					].detail.reduce(function(item, next) {
						/* eslint-disable */
						hash[next] ? "" : (hash[next] = true && item.push(next));
						return item;
					}, []);
				} else {
					this.$Message.warning("请添加属性");
				}
			},
		},
	};
</script>

<style scoped lang="stylus">
	.rulesBox {
		display: flex;
		align-items center;
		flex-wrap: wrap;
	}

	.attrFrom {
		>>>.ivu-form-item {
			margin-bottom: 0px !important;
		}
	}

	.sub {
		text-align right margin 20px 0 0 20px
	}

	.vertical-layout {
		display: block !important;
		/* 覆盖默认的 flex 布局 */
	}

	/* 标签样式 */
	.vertical-layout>>>.ivu-form-item-label {
		float: none !important;
		/* 取消浮动 */
		display: block !important;
		/* 块级显示 */
		width: 100% !important;
		/* 占满宽度 */
		text-align: left !important;
		/* 左对齐 */
		padding: 0 0 10px 0 !important;
		/* 底部间距 */
		margin-bottom: 10px;
		/* 增加与内容的间距 */
		border-bottom: 1px solid #eee;
		/* 可选：添加分隔线 */
		font-weight: bold;
		/* 加粗显示 */
	}

	/* 内容区域样式 */
	.vertical-layout>>>.ivu-form-item-content {
		display: block !important;
		/* 块级显示 */
		margin-left: 0 !important;
		/* 清除左侧间距 */
		clear: both;
		/* 清除浮动 */
	}

	.discount-medium {
		background-color: #ebf5ff;
		color: #1890ff;
	}

	.discount-low {
		background-color: #fef3e8;
		color: #fa8c16;
	}

	.stock-warning {
		color: #e74c3c;
		font-weight: 500;
	}

	.text-center {
		text-align: center;
	}

	.text-right {
		text-align: right;
	}

	.table-container {
		background: white;
		border-radius: 10px;
		box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
		overflow: hidden;
		margin-bottom: 30px;
	}

	.table-header {
		padding: 15px 20px;
		background: #f8f9fa;
		border-bottom: 1px solid #e9ecef;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.table-title {
		font-size: 18px;
		font-weight: 600;
		color: #2c3e50;
	}

	.table-actions {
		display: flex;
		gap: 10px;
	}

	.btn {
		padding: 8px 16px;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		font-weight: 500;
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		gap: 5px;
	}

	.btn-primary {
		background: #6a11cb;
		color: white;
	}

	.btn-primary:hover {
		background: #5a0fb8;
	}

	.btn-outline {
		background: transparent;
		border: 1px solid #6a11cb;
		color: #6a11cb;
	}

	.btn-outline:hover {
		background: #f0e6ff;
	}

	table {
		width: 100%;
		border-collapse: collapse;
	}

	th,
	td {
		padding: 12px 15px;
		text-align: left;
		border-bottom: 1px solid #e9ecef;
	}

	th {
		background-color: #f8f9fa;
		font-weight: 600;
		color: #2c3e50;
		position: sticky;
		top: 0;
	}

	tr:hover {
		background-color: #f8f9fa;
	}
	/* 仓库信息样式 */
	.warehouse-info {
	    display: flex;
	    justify-content: space-between;
	    margin-bottom: 4px;
	    padding: 2px 4px;
	}
	
	.warehouse-info:last-child {
	    margin-bottom: 0;
	}
	
	.warehouse-name {
	    font-size: 12px;
	    color: #666;
	}
	
	.warehouse-stock {
	    font-weight: bold;
	}
	
	/* 活动库存输入框样式 */
	.activity-stock-input {
	    margin-bottom: 8px;
	    text-align: center;
	}
	
	.activity-stock-input:last-child {
	    margin-bottom: 0;
	}
	
	.stock-input {
	    width: 80px;
	    margin: 0 auto 2px;
	}
	
	.warehouse-label {
	    font-size: 11px;
	    color: #888;
	    margin-top: 2px;
	}
	
	/* 库存警告样式 */
	.stock-warning {
	    background-color: #fff2f0;
	    border-left: 3px solid #ff4d4f;
	}
	
	/* 折扣标签样式 */
	.discount-badge {
	    background-color: #f6ffed;
	    border: 1px solid #b7eb8f;
	    color: #52c41a;
	    padding: 2px 6px;
	    border-radius: 4px;
	    font-size: 12px;
	    font-weight: bold;
	}
	
	/* 价格样式 */
	.original-price {
	    text-decoration: line-through;
	    color: #999;
	    font-size: 12px;
	}
	
	.sale-price {
	    color: #ff4d4f;
	    font-weight: bold;
	    font-size: 14px;
	}
</style>